package com.gateway.route;

import cn.hutool.json.JSONUtil;
import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executor;

@Slf4j
@Component
@RequiredArgsConstructor
public class DynamicRouterLoader {
    private final NacosConfigManager nacosConfigManager;
    private final String dataId ="gateway-route.json";
    private final String groupId ="DEFAULT_GROUP";
    private final Set<String> routeIds =new HashSet<>();
    private final RouteDefinitionWriter routeDefinitionWriter;

    @PostConstruct
    public void init() throws NacosException {
        //1.创建nacosManagement
        String stringConfigInfo = nacosConfigManager.getConfigService()
                .getConfigAndSignListener(dataId, groupId, 5000, new Listener() {
                    @Override
                    public Executor getExecutor() {
                        return null;
                    }

                    @Override
                    public void receiveConfigInfo(String s) {
                        //2.监听到变化时读取一次配置
                        updateConfigInfo(s);
                    }
                });
        //3.初始化时读取一次配置
        updateConfigInfo(stringConfigInfo);
    }

    private void updateConfigInfo(String stringConfigInfo)
    {
        log.info("路由变化。。。。。。。。。。。。。。。。。。。:{}",stringConfigInfo);
        //1.解析配置信息
        List<RouteDefinition> routeDefinitionList = JSONUtil.toList(stringConfigInfo, RouteDefinition.class);

        //2.删除历史路由
        for (String routeId : routeIds) {
            routeDefinitionWriter.delete(Mono.just(routeId)).subscribe();
        }
        routeIds.clear();
        //3.更新路由信息
        //3.1判断是否为空
        if (routeDefinitionList.isEmpty())
        {
            return;
        }
        for (RouteDefinition routeDefinition : routeDefinitionList) {
            routeDefinitionWriter.save(Mono.just(routeDefinition)).subscribe();

            routeIds.add(routeDefinition.getId()) ;
        }
    }
}
